package top.sjydzq.www.controller.Mall;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import top.sjydzq.www.bean.Order;
import top.sjydzq.www.bean.OrderItem;
import top.sjydzq.www.service.CartService;
import top.sjydzq.www.service.OrderService;
import top.sjydzq.www.service.ProductService;

@Controller
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private ProductService productService;

    @RequestMapping("add")
    public String add(int uid) {
        if (orderService.addOrder(uid)) {
            cartService.clear(uid);

            return String.format("redirect:/order/confirm?uid=%d&id=%d", uid, orderService.selectLastId(uid));
        } else {
            return "Mall/Order/failed";
        }
    }

    @RequestMapping("confirm")
    public String confirm(int uid, int id, Model model) {
        Order order = orderService.selectById(id, uid);

        model.addAttribute("order", order);

        return "Mall/Order/confirm";
    }

    @RequestMapping("done")
    public  String done(int oid, int uid, Model model) {
        Order order = orderService.selectById(oid, uid);

        for (OrderItem item: order.getItems()) {
            productService.minusStoreAmount(item.getProductId(), item.getAmount());
        }

        model.addAttribute("oid", oid);

        return "Mall/Order/done";
    }

    @RequestMapping("payed")
    public  String payed(int oid) {
        orderService.setOrderStatus(oid, 1);

        return "Mall/Order/payed";
    }

    @RequestMapping("detail")
    public String detail(int uid, int id, Model model) {
        Order order = orderService.selectById(id, uid);

        model.addAttribute("order", order);

        return "Mall/Order/detail";
    }
}
